import Icon from '@/components/Icon'
import { changeActive, getUserChannels } from '@/store/actions/home'
import { RootState } from '@/types/store'
import { useInitialState } from '@/utils/hooks'
import { Tabs, Popup } from 'antd-mobile'
import { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import Channels from './components/Channels'
import ArticleList from './components/ArticleList'
import { useHistory } from 'react-router-dom'

import styles from './index.module.scss'

const Home = () => {

  const {userChannels} = useInitialState(getUserChannels, 'home')
  const [visible, setVisible] = useState(false);
  const {activeKey} = useSelector((state: RootState) => state.home);
  const dispatch = useDispatch()

  const history = useHistory()

  const onShow = () => {
    setVisible(true)
  }

  const onHide = () => {
    setVisible(false)
  }

  const changeTab = (key: string) => {
    dispatch(changeActive(+key))
  }

  return (
    <div className={styles.root}>
      {/* 频道 Tabs 列表 */}
      <Tabs className='tabs' activeKey={activeKey + ''} onChange={changeTab}>
        {
          userChannels.length && userChannels.map((channel) => (
            <Tabs.Tab title={channel.name} key={channel.id}>
              <ArticleList channelId={channel.id}/>
            </Tabs.Tab>
          ))
        }
      </Tabs>
      <div className="tabs-opration">
        <Icon type="iconbtn_search" onClick={() => {
          history.push('/search')
        }}/>
        <Icon type="iconbtn_channel" onClick={onShow}/>
      </div>
      <Popup position='left' visible={visible}>
        <Channels onHide={onHide}></Channels>
      </Popup>
    </div>
  )
}

export default Home
